from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection
from django.contrib.auth import login, logout
from django.contrib.auth import authenticate
from django.conf import settings
from django.utils.decorators import method_decorator
import logging
import json
import re
from django.core.mail import send_mail

from users.models import User, check_verify_email, Address
from meiduo_mall.utils.view import login_required, LoginRequiredJsonMixin
from celery_tasks.emails.tasks import send_verify_email
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis

# Create your views here.
# 创建日志生成器
logger = logging.getLogger('django')


class ChangePasswordView(LoginRequiredJsonMixin, View):
    def put(self, request):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        if not all([old_password, new_password, new_password2]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', old_password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', new_password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})
        if new_password != new_password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次密码不同'})

        if not request.user.check_password(old_password):
            return http.JsonResponse({'code': 400, 'errmsg': '密码输入有误'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '密码修改失败'})

        # 清理状态保持
        logout(request)
        response = http.JsonResponse({'code': 0, 'errmsg': '密码修改成功'})
        # 清除前端cookie
        response.delete_cookie('username')
        return response


class UpdateTitleAddressView(View):
    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        if not title:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数'})
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '标题修改失败'})
        return http.JsonResponse({'code': 400, 'errmsg': '标题修改成功'})


class DefaultAddressView(LoginRequiredJsonMixin, View):
    """修改默认地址"""
    def put(self, request, address_id):
        try:
            # 这种有点多余
            # user = User.objects.get(id=request.user.id)
            # user.default_address_id = address_id
            # user.save()
            address = Address.objects.get(id=address_id)
            request.user.default_address = address  # 注意
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '默认地址修改失败'})

        return http.JsonResponse({'code': 0, 'errmsg': '默认地址修改成功'})


class UpdateDestroyAddressView(View):
    """修改\删除地址"""

    def delete(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            # 补充逻辑,删除默认地址,默认信息也要删掉
            if address.user.default_address == address:
                address.user.default_address = None
                address.user.save()
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '删除失败'})
        return http.JsonResponse({'code': 0, 'errmsg': '删除成功'})

    def put(self, request, address_id):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile参数格式有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': 'tel参数格式有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': 'email参数格式有误'})

        try:
            # address = Address.objects.get(id=address_id)
            # address.user = request.user
            # address.province_id = province_id
            # address.city_id = city_id
            # address.district_id = district_id
            # address.title = receiver
            # address.receiver = receiver
            # address.place = place
            # address.mobile = mobile
            # address.tel = tel
            # address.email = email
            # address.save()

            # 更新无法创建对象
            Address.objects.filter(id=address_id).update(
                user = request.user,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                title = receiver,
                receiver = receiver,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '地址修改失败'})

        address = Address.objects.get(id=address_id)
        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})


class AddressView(LoginRequiredJsonMixin, View):
    def get(self, request):
        addresses = Address.objects.filter(user=request.user, is_deleted=False)
        addresses_list = []
        for address in addresses:
            address_dict = {
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            }
            if request.user.default_address == address:
                addresses_list.insert(0, address_dict)
            else:
                addresses_list.append(address_dict)

        default_address_id = request.user.default_address_id

        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'default_address_id': default_address_id,
            'addresses': addresses_list
        })


class CreateAddressView(LoginRequiredJsonMixin, View):
    def post(self, request):
        # 补充逻辑--限制地址个数不可超过20个
        count = Address.objects.filter(user=request.user, is_deleted=False).count()
        print(count)
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '地址个数超过20个'})

        # 提取参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile参数格式有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': 'tel参数格式有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': 'email参数格式有误'})

        address = Address.objects.create(
            user=request.user,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            title=receiver,
            receiver=receiver,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )
        # 默认地址设置
        if not request.user.default_address:
            request.user.default_address = address
            request.user.save()

        address_list = [{
            'id': address.id,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }]

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_list})


class UserBrowseHistory(LoginRequiredJsonMixin, View):
    """用户浏览记录"""
    def get(self, request):
        conn = get_redis_connection('history')
        redis_skus = conn.lrange('histories_%s' % request.user.id, 0, -1)
        skus = []
        for sku_id in redis_skus:
            try:
                sku = SKU.objects.get(id=sku_id)
                # sku = SKU.objects.get(id=int(sku_id))
            except Exception as e:
                logger.error(e)
                # 某个数据不存在,继续下一个
                continue
            if not sku.is_launched:
                # 某个数据下架,继续下一个
                continue

            skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price
            })
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': skus})

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        if not sku_id:
            return http.JsonResponse({'code': 400, 'errmsg': '数据不存在'})
        if not sku_id.isdigit():
            return http.JsonResponse({'code': 400, 'errmsg': '数据有误'})

        try:
            SKU.objects.get(id=int(sku_id))
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '商品不存在'})

        conn = get_redis_connection('history')
        # 创建管道
        pl = conn.pipeline()
        try:
            # 先去重再增加
            pl.lrem('histories_%s' % request.user.id, 0, sku_id)
            # 往前插入浏览记录
            pl.lpush('histories_%s' % request.user.id, sku_id)
            # 保留5个浏览记录
            pl.ltrim('histories_%s' % request.user.id, 0, 4)
            # 执行管道
            pl.execute()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据保存失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class VerifyEmailView(View):
    def put(self, request):
        token = request.GET.get('token')
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': '链接无效'})

        user = check_verify_email(token)
        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '无效token'})
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '无法保存'})
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class EmailView(LoginRequiredJsonMixin, View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数'})

        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': 'email格式有误'})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        # 异步方案解耦发送邮件和响应
        verify_url = request.user.generate_verify_email_url()
        send_verify_email.delay(email, verify_url)
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class UserInfoView(LoginRequiredJsonMixin, View):
    # 使用装饰器判断是否登录
    # @method_decorator(login_required)
    def get(self, request):
        # 进入用户中心之前,先判断用户是否登录
        # request.user是django封装好登录用户的对象,可以直接用它获取用户属性
        # if not request.user.is_authenticated:
        #     return http.JsonResponse({'code': 400, 'errmsg': '用户未登录'})
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})


class LogoutView(View):
    def delete(self, request):
        # 退出登录
        logout(request)
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 删除前端的cookie缓存
        response.delete_cookie('username')
        return response


class LoginView(View):
    def post(self, request):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 校验参数
        if not all([username, password]):
            return http.JsonResponse({'code': 0, 'errmsg': '缺少必要参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误'})

        # 多账号登录,通过修改django底层原理,实现多账号登录,默认是用户名登录
        # if re.match(r'^1[3-9]\d{9}$', username):
        #     User.USERNAME_FIELD = 'mobile'
        # else:
        #     User.USERNAME_FIELD = 'username'

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})

        if not isinstance(remembered, bool):
            return http.JsonResponse({'code': 400, 'errmsg': 'remembered格式有误'})

        # # 常规方法创建用户对象来判断用户是否登录
        # try:
        #     user = User.objects.get(username=username)
        # except Exception as e:
        #     logger.error(e)
        #     return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
        # if not user.check_password(password):
        #     return http.JsonResponse({'code': 400, 'errmsg': '密码错误'})

        # 使用django自带认证方法
        user = authenticate(username=username, password=password)

        if not user:
            return http.JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
        # 状态保持
        login(request, user)

        # 构造响应
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 判断是否记录登录用户
        if remembered:
            request.session.set_expiry(None)
            response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        else:
            request.session.set_expiry(0)
            response.set_cookie('username', user.username)
        # response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        # response.set_cookie('username', user.username, max_age=3600*24*14)
        # 返回响应
        # return response
        return merge_cart_cookie_to_redis(request, user, response)


class RegisterView(View):
    def post(self, request):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        sms_code = json_dict.get('sms_code')
        allow = json_dict.get('allow')

        # 校验参数
        if not all([username, password, password2, mobile, sms_code]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})

        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次密码不同'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})

        conn = get_redis_connection('verify_code')
        # redis返回的是字节类型
        sms_code_server = conn.get('sms_%s' % mobile)
        # 判断数据库提取的数据是否存在
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '验证码过期'})
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '输入验证码有误'})

        # isinstance(allow, bool)判断allow = True/False时,
        # 返回True/False,若allow=非布尔数据,返回False,  确定是布尔字段才可以使用它进行过滤
        if not isinstance(allow, bool):
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误'})

        if not allow:
            return http.JsonResponse({'code': 400, 'errmsg': '没有勾选协议'})

        # 保存数据到数据库
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '保存数据失败'})

        # 状态保持
        login(request, user)

        # 首页用户缓存
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)

        return merge_cart_cookie_to_redis(request, user, response)


class MobileCountView(View):
    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})


class UsernameCountView(View):
    def get(self, request, username):
        # 路径已经校验username,则无需再校验
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count})

